package com.tsingteng.cosfun.ui.costar;

import android.app.Activity;
import android.content.Intent;
import android.opengl.GLSurfaceView;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;


import com.pili.pldroid.player.widget.PLVideoView;
import com.qiniu.pili.droid.shortvideo.PLAudioEncodeSetting;
import com.qiniu.pili.droid.shortvideo.PLDisplayMode;
import com.qiniu.pili.droid.shortvideo.PLMediaFile;
import com.qiniu.pili.droid.shortvideo.PLShortVideoEditor;
import com.qiniu.pili.droid.shortvideo.PLVideoEditSetting;

import com.qiniu.pili.droid.shortvideo.PLVideoPlayerListener;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.base.BaseActivity;
import com.tsingteng.cosfun.helper.VideoHelper;
import com.tsingteng.cosfun.utils.DateUtils;
import com.tsingteng.cosfun.utils.LogUtils;
import com.tsingteng.cosfun.utils.LogonUtils;
import com.tsingteng.cosfun.utils.TimeUtils;
import com.tsingteng.cosfun.widget.dialog.VideoSliceSelectDialog;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 描述 :翻拍
 * 创建人: 肖利.
 * 时间:2018/8/10
 * qq(872179966)
 */

public class BeforeFilmActivity extends BaseActivity implements PLVideoPlayerListener , com.tsingteng.cosfun.widget.dialog.VideoSliceSelectDialog.OnDialogDissMissListener {
    @BindView(R.id.preview)
    GLSurfaceView preview;
    @BindView(R.id.tv_time)
    TextView textTime;
    @BindView(R.id.iv_close)
    ImageView close;
    @BindView(R.id.record_progressbar)
    ProgressBar recordProgressbar;
    @BindView(R.id.iv_video_cover)
    ImageView ivVideoCover;
    @BindView(R.id.iv_play)
    ImageView mIvPlay;
    private long time;
    private PLVideoEditSetting setting;
    private PLShortVideoEditor mShortVideoEditor;
    private String mMp4path;
    private long mMixDuration;
    private PLShortVideoEditorStatus mShortVideoEditorStatus = PLShortVideoEditorStatus.Idle;
    private Timer timerTask;
    private TimerTask taskTimer;
    private boolean isStart = true;
    private VideoSliceSelectDialog VideoSliceSelectDialog;
    private boolean isBackVideo = false;


    @Override
    public void onCompletion() {
        time = 0;
    }

    @Override
    public void onDissMiss() {

    }


    // 视频编辑器预览状态
    private enum PLShortVideoEditorStatus {
        Idle,
        Playing,
        Paused,
    }

    @Override
    protected void initView() {
        setting = new PLVideoEditSetting();
        setting.setSourceFilepath(mMp4path);
        setting.setDestFilepath(VideoHelper.EDITED_FILE_PATH);
        mShortVideoEditor = new PLShortVideoEditor(preview, setting);
        mShortVideoEditor.setVideoPlayerListener(this);
        mShortVideoEditor.setDisplayMode(PLDisplayMode.FULL);//设置满屏
        mMixDuration = mShortVideoEditor.getDurationMs();
        LogUtils.i("mMixDuration+ BeforeFilmActivity" + mMixDuration);
        recordProgressbar.setMax((int) mMixDuration);
        VideoSliceSelectDialog = new VideoSliceSelectDialog(this, 2);
        VideoSliceSelectDialog.setOnDialogDissMissListener(this);
        close.setOnClickListener(v -> {
            VideoHelper.getIntence().setCurrentVideoPosition(-1);
            finish();
        });
        startTimer();
        startPlayback();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_film_beafore;
    }

    @Override
    protected void getIntentData(Intent intent) {
        mMp4path = intent.getStringExtra(VideoHelper.VIDEO_PATH);
        isFullScreen = true;
    }


    @OnClick({R.id.preview, R.id.iv_video_cover, R.id.bt_fan_pai, R.id.bt_resever, R.id.iv_to_shoot})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.preview:
                if (isStart) {
                    pausePlayback(true);
                    if (timerTask != null) {
                        taskTimer.cancel();
                    }
                } else {
                    startPlayback();
                    timerTask = null;
                    taskTimer = null;
                    startTimer();
                }
                isStart = !isStart;
                break;
            case R.id.iv_video_cover:
                if (VideoSliceSelectDialog == null) VideoSliceSelectDialog = new VideoSliceSelectDialog(this,2);
                VideoSliceSelectDialog.show();
                new Handler().postDelayed(() -> VideoSliceSelectDialog.refreshData(), 50);
                break;
            case R.id.bt_fan_pai://原生翻拍
                VideoHelper.getIntence().setFanPai(true);
                VideoHelper.getIntence().setVideoAudioPath(mMp4path);
                finish();
                break;
            case R.id.bt_resever://改编本段
                finish();
                break;
            case R.id.iv_to_shoot:
                VideoHelper.getIntence().setCurrentVideoPosition(-1);
                finish();
                break;
        }
    }

    /**
     * 启动预览
     */
    private void startPlayback() {
        mIvPlay.setVisibility(View.GONE);
        if (mShortVideoEditorStatus == PLShortVideoEditorStatus.Idle) {
            mShortVideoEditor.startPlayback();
            mShortVideoEditorStatus = PLShortVideoEditorStatus.Playing;
        } else if (mShortVideoEditorStatus == PLShortVideoEditorStatus.Paused) {
            mShortVideoEditor.resumePlayback();
            mShortVideoEditorStatus = PLShortVideoEditorStatus.Playing;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        startPlayback();
        VideoHelper.getIntence().setFanPai(false);
        VideoHelper.getIntence().setVideoAudioPath(null);
        if (taskTimer != null) {
            taskTimer.run();
        }
        ivVideoCover.setImageBitmap(VideoHelper.getIntence().getVideoThumbnail(mMp4path));
    }

    @Override
    protected void onPause() {
        super.onPause();
        pausePlayback(false);
        if (taskTimer != null) {
            taskTimer.cancel();
        }
        if (timerTask != null) {
            timerTask.cancel();

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopPlayback();
        if (mShortVideoEditor != null) {
            mShortVideoEditor.pausePlayback();
        }

        if (taskTimer != null) {
            taskTimer.cancel();
            taskTimer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    /**
     * 停止预览
     */
    private void stopPlayback() {
        mShortVideoEditor.stopPlayback();
        mShortVideoEditorStatus = PLShortVideoEditorStatus.Idle;
    }

    /**
     * 暂停预览
     */
    private void pausePlayback(boolean isClick) {
        if (isClick)
        mIvPlay.setVisibility(View.VISIBLE);
        mShortVideoEditor.pausePlayback();
        mShortVideoEditorStatus = PLShortVideoEditorStatus.Paused;
    }

    private void startTimer() {
        timerTask = new Timer();
        taskTimer = new TimerTask() {
            @Override
            public void run() {
                time = time + 10;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        textTime.setText(DateUtils.div(time,1000,1)+"s");
                        if (recordProgressbar != null)
                            recordProgressbar.setProgress((int) time);
                    }
                });
            }
        };
        timerTask.schedule(taskTimer, 0, 10);
    }

    public void showSliceSelectDialog() {
        if (VideoSliceSelectDialog == null) return;
        VideoSliceSelectDialog.refreshData();
    }

    public void dissSliceSelectDialog() {
        if (VideoSliceSelectDialog == null) return;
        VideoSliceSelectDialog.dissMiss();
    }

    /**
     * 重新设置地址
     * @param videoPath
     */
    private void setNewVideoPath(String videoPath){
        if (TextUtils.isEmpty(videoPath))return;
        if (mShortVideoEditor == null) return;
        if (setting!=null) {
            setting=null;
        }
        setting = new PLVideoEditSetting();
        setting.setSourceFilepath(videoPath);
        setting.setDestFilepath(VideoHelper.VIDEO_SHOOT + System.currentTimeMillis() + LogonUtils.getProFildId() + "cos_fun.mp4");
//        mShortVideoEditor = new PLShortVideoEditor(mPreviewView);
        mShortVideoEditor.setVideoEditSetting(setting);

        mShortVideoEditor.setDisplayMode(PLDisplayMode.FULL);
        startPlayback();
        mMp4path= videoPath;
        timerTask = null;
        taskTimer = null;
        LogUtils.e("countDownTimer444444", time + "");
        startTimer();
    }
}
